package com.albert.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static com.albert.thread.ThreadPool.service;

public class CompletableFutureThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //异步编排
        System.out.println("开始");

        //没有返回结果
        /*CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("执行线程任务");
        }, service);*/

        //supplyAsync 有返回结果
        //whenComplete  exceptionally  结果的感知   抛异常
        /*CompletableFuture<Integer> returnNum = CompletableFuture.supplyAsync(() -> {
            System.out.println("有返回结果");
            return 10 / 0;
        }, service).whenComplete((res,exception)->{
            //虽然可以得到结果却无法修改,相当于一个监听器
            System.out.println("结果是:"+res+"异常"+exception);
        }).exceptionally(throwable->{
            return 10;
        });*/

        //handle   方法执行完之后的处理
        CompletableFuture<Integer> returnHand = CompletableFuture.supplyAsync(() -> {
            System.out.println("有返回结果");
            return 10 / 0;
        }, service).whenComplete((res,exception)->{
            //虽然可以得到结果却无法修改,相当于一个监听器
            System.out.println("结果是:"+res+"异常"+exception);
        }).handle((res,exception)->{
            if(res!=null){
                return 100;
            }if(exception!=null){
                return 99;
            }
            return 0;
        });
        //System.out.println("得到数字"+returnNum.get());
        System.out.println("结束"+returnHand.get());
    }
}
